package com.easyfun.healthmagicbox;

import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.easyfun.healthmagicbox.base.BaseActivity;
import com.easyfun.healthmagicbox.base.DatabaseAccess;
import com.easyfun.healthmagicbox.base.DatabaseAccessImplementation;
import com.easyfun.healthmagicbox.comm.HealthInputDataDeleteTask;
import com.easyfun.healthmagicbox.comm.HealthThreadPool;
import com.easyfun.healthmagicbox.inputviews.DietInputActivity;
import com.easyfun.healthmagicbox.inputviews.FitnessInputActivity;
import com.easyfun.healthmagicbox.inputviews.HardwareInputActivity;
import com.easyfun.healthmagicbox.inputviews.PhysicalExamInputActivity;
import com.easyfun.healthmagicbox.inputviews.TakeAPictureActivity;
import com.easyfun.healthmagicbox.inputviews.VoiceInputActivity;
import com.easyfun.healthmagicbox.ormlite.DatabaseHelper;
import com.easyfun.healthmagicbox.pojo.ConstantData;
import com.easyfun.healthmagicbox.pojo.HealthInputData;
import com.easyfun.healthmagicbox.pojo.PersonProfile;
import com.easyfun.healthmagicbox.pojo.UserToPersons;
import com.easyfun.healthmagicbox.sync.BasicCommCallback;
import com.easyfun.healthmagicbox.util.PersonProfileCache;
import com.easyfun.healthmagicbox.util.URIConverter;
import com.easyfun.healthmagicbox.widget.DialogBuilder;
import com.easyfun.healthmagicbox.widget.DialogBuilder.OnDialogButtonClickListener;
import com.easyfun.healthmagicbox.widget.SelectInputCatalogPopupWindow;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.stmt.QueryBuilder;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.util.Log;
import android.util.SparseIntArray;
import android.view.Gravity;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

public class SubLastProfileActivity extends BaseActivity implements
		DatabaseAccess {

	private final String LOG_TAG = getClass().getSimpleName();

	private ImageView m_imageHead;
	private String imagefilename;
	//EditText txtShareCode ;
	TextView txtSharelist;
	TextView seperator2;
	//
	SelectInputCatalogPopupWindow menuWindow;

	private TextView seperator_share;
	ListView listLastActs;

	private ArrayAdapter<String> mInputAdapter;

	DatabaseHelper databaseHelper;
	SparseIntArray inputlistIDs = new SparseIntArray();

	private String mSex = "男"; 

	void loadData()
	{
		try {
			Dao<PersonProfile, Integer> profileDao = getHelper(this).getPersonProfileDao();
			List<PersonProfile> pps;
		
			pps = profileDao.queryForEq("personID", m_personid);
		
			if (pps.size()==1)
			{
				final PersonProfile pp = pps.get(0);
				
				if ((pp.getSex() != null)&&(pp.getSex().length()!=0))	
					mSex = pp.getSex();
					
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	@Override
	protected void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		setContentView(R.layout.one);
		if (!checkPersonId())
			return;
		
		listLastActs = (ListView) findViewById(R.id.lastactlistview);
		//Button butShareIt = (Button) findViewById(R.id.butsendsharecode);
		//txtShareCode = (EditText) findViewById(R.id.txtShareCode);
		seperator_share = (TextView) findViewById(R.id.seperator_share);
		txtSharelist = (TextView) findViewById(R.id.txtSharelist);
		seperator2 = (TextView) findViewById(R.id.seperator2);
		
		
		mInputAdapter = new ArrayAdapter<String>(this,
					R.layout.one_lastinputlistitem,
					R.id.lastinputtitem_info,
					new ArrayList<String>());
					
		/*mInputAdapter = new CustomListItemAdaptor(this,
				R.layout.one_lastinputlistitem,
				new ArrayList<String>(), true);
				*/
		
		getLastInputActs(mInputAdapter);

		mInputAdapter.setNotifyOnChange(true);
		listLastActs.setAdapter(mInputAdapter);

		
		listLastActs.setOnItemLongClickListener(new OnItemLongClickListener() {

			@Override
			public boolean onItemLongClick(AdapterView<?> parent, View view,
					int position, long id) {
				final Integer inputid = inputlistIDs.get(position);
				if ((inputlistIDs.size()==0)||(inputid == 0))
					return false;
				new DialogBuilder(SubLastProfileActivity.this)
					.setTitle("是否删除")
					.setMessage(mInputAdapter.getItem(position).toString())
					.setButtons("确定", "取消", new OnDialogButtonClickListener() {
						
						@Override
						public void onDialogButtonClick(Context context, DialogBuilder builder,
								Dialog dialog, int dialogId, int which) {
							if (which == BUTTON_LEFT)
							{
								try {
									Dao<HealthInputData, Integer> inputdao = getHelper(SubLastProfileActivity.this).getInputDataDao();
									HealthInputData hid = inputdao.queryForId(inputid);
									inputdao.deleteById(inputid);
									getLastInputActs(mInputAdapter);					
									mInputAdapter.notifyDataSetChanged();
									HealthInputDataDeleteTask task = new
											HealthInputDataDeleteTask(hid.getSyncid().toString(),
													SubLastProfileActivity.this,
													new BasicCommCallback());
									HealthThreadPool.getInstance().execute(task);
								} catch (SQLException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								}
							}
							else
							{
								dialog.dismiss();
							}
						}
					}).create().show();;
				
				return true;
			}
		});
		
		
		
		listLastActs.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				final Integer inputid = inputlistIDs.get(position);
				if ((inputlistIDs.size()==0)||(inputid == 0))
					return ;
				final Intent intent_pp = new Intent(
						SubLastProfileActivity.this, InputsCatagoryActivity.class);
				intent_pp.putExtra(ConstantData.HMBPERSONID, m_personid);
				HealthInputData hid;
				try {
					Dao<HealthInputData, Integer> inputdao = getHelper(SubLastProfileActivity.this).getInputDataDao();
					hid = inputdao.queryForId(inputid);
				} catch (SQLException e) {
					
					e.printStackTrace();
					return;
				}
				if (hid!=null)
				{
					Integer inputtype = hid.getValueType();
					if (inputtype!=null)
					{
						intent_pp.putExtra(ConstantData.INPUT_TYPE, inputtype.toString());
							SubLastProfileActivity.this.startActivity(intent_pp);
					}				
				}
			}
				
		}
				);
		
		

		Button butInputData = (Button) findViewById(R.id.butInputData);

		// show big head image
		m_imageHead = (ImageView) findViewById(R.id.lastimagehead);

		try {
			Dao<PersonProfile, Integer> dao = getHelper(this)
					.getPersonProfileDao();
			List<PersonProfile> pps;
			pps = dao.queryBuilder().where().eq("personID", m_personid).query();
			if (pps.size() >= 1) {
				imagefilename = pps.get(0).getImageFileName();
				Bitmap img = URIConverter.getHeadFromAppSDCard(this,
						imagefilename,pps.get(0).getPersonID(),pps.get(0).getSex());
				m_imageHead.setImageBitmap(img);
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		m_imageHead.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				final Intent intent_pp = new Intent(
						SubLastProfileActivity.this, ProfileActivity.class);
				intent_pp.putExtra(ConstantData.HMBPERSONID, m_personid);
				SubLastProfileActivity.this.startActivity(intent_pp);
			}
		});

		butInputData.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				// SelectPicPopupWindow
				menuWindow = new SelectInputCatalogPopupWindow(
						SubLastProfileActivity.this, itemsOnClick);
				//
				menuWindow.showAtLocation(SubLastProfileActivity.this
						.findViewById(R.id.viewone_top_layout), Gravity.BOTTOM
						| Gravity.CENTER_HORIZONTAL, 0, 0);
				//
			}
		});
		
		loadData();
		
//		butShareIt.setOnClickListener(new OnClickListener() {
//			public void onClick(View v) {
//				shareIt();
//			}
//
//		});
	}

	
	
	
	
	//
	private OnClickListener itemsOnClick = new OnClickListener() {

		public void onClick(View v) {
			menuWindow.dismiss();

			switch (v.getId()) {
			case R.id.btn_fitness_data:
				final Intent intent = new Intent(SubLastProfileActivity.this,
						FitnessInputActivity.class);
				intent.putExtra(ConstantData.HMBPERSONID, m_personid);
				SubLastProfileActivity.this.startActivity(intent);
				break;
			case R.id.btn_health_data:
				final Intent intent_health = new Intent(
						SubLastProfileActivity.this,
						PhysicalExamInputActivity.class);
				intent_health.putExtra(ConstantData.HMBPERSONID, m_personid);
				SubLastProfileActivity.this.startActivity(intent_health);
				break;
			case R.id.btn_voice_data:
				Toast.makeText(SubLastProfileActivity.this, "敬请期待", Toast.LENGTH_SHORT);
				/*
				final Intent intent_voice = new Intent(
						SubLastProfileActivity.this, VoiceInputActivity.class);
				intent_voice.putExtra(ConstantData.HMBPERSONID, m_personid);
				SubLastProfileActivity.this.startActivity(intent_voice);
				*/
				break;
			case R.id.btn_picture_data:
				final Intent intent_pic = new Intent(
						SubLastProfileActivity.this, TakeAPictureActivity.class );//PictureTessActivity.class
				intent_pic.putExtra(ConstantData.HMBPERSONID, m_personid);
				SubLastProfileActivity.this.startActivity(intent_pic);
				break;
			case R.id.btn_eat_data:
				final Intent intent_eat = new Intent(
						SubLastProfileActivity.this, DietInputActivity.class);
				intent_eat.putExtra(ConstantData.HMBPERSONID, m_personid);
				SubLastProfileActivity.this.startActivity(intent_eat);
				break;
			case R.id.btn_hardware_data:
				final Intent intent_hardware = new Intent(
						SubLastProfileActivity.this, HardwareInputActivity.class);
				intent_hardware.putExtra(ConstantData.HMBPERSONID, m_personid);
				SubLastProfileActivity.this.startActivity(intent_hardware);
				break;
			default:
				break;
			}

		}

	};
	private void getLastInputActs(
			ArrayAdapter<String> inputAdapter) {
		inputAdapter.clear();
		int i = 0;
		// get our dao
		try {
			Dao<HealthInputData, Integer> inputDao = getHelper(this)
					.getInputDataDao();
			List<HealthInputData> pps = inputDao.queryBuilder()
					.orderBy("valueTime", false).where()
					.eq("personID", getPersonid()).query();
			// List<HealthInputData> pps = inputDao.queryForEq("personid",
			// getPersonid());

			for (HealthInputData input : pps) {
				SimpleDateFormat sdf = new SimpleDateFormat("MM-dd HH:mm");
				// 前面的lSysTime是秒数，先乘1000得到毫秒数，再转为java.util.Date类型
				java.util.Date dt = new Date(Long.valueOf(input.getValueTime())
						.longValue());
				String time = sdf.format(dt); // 得到精确到秒的表示：08/31/2006 21:08:00

				// String time = String.format(Locale.CHINA,"%tm-%td %tH:%tM",
				// );
				if (ConstantData.IdToNameMapping.get(input.getValueType()) != null)
				{
					String value = String.format(ConstantData.IdToNameMapping.get(input.getValueType())
						,
						input.getValueData());
					inputAdapter.add(time + " " + value);
					inputlistIDs.put(i, Integer.valueOf(input.getId()));
					i++;
				}
				if (i > 50) {
					break;
				}
			}
			Log.i(LOG_TAG, "get last input data.");

		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		if (i == 0)
			inputAdapter.add("还没有健康数据");
		return;
	}


	@Override
	public void onWindowFocusChanged(boolean hasFocus) {
		if (hasFocus) {
			// picture has updated.
			m_imageHead.refreshDrawableState();
			Bitmap img = URIConverter.getHeadFromAppSDCard(this,
					imagefilename,"",mSex);
			m_imageHead.setImageBitmap(img);
			m_imageHead.refreshDrawableState();
			m_imageHead.invalidate();
			getLastInputActs(mInputAdapter);
			
			mInputAdapter.notifyDataSetChanged();
		}
	}

	@Override
	public DatabaseHelper getHelper(Context context) {

		return DatabaseAccessImplementation.getInstance().getHelper(context);
	}
	@Override  
    public boolean onOptionsItemSelected(MenuItem item) {  
       
        return super.onOptionsItemSelected(item,this);  
    }  
	
	
}
